using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace hao_Common.Consul.Services
{
    /// <summary>
    /// Consul 后台服务
    /// 实现 IHostedService 接口，在应用启动时自动注册服务，在应用停止时自动注销服务
    /// </summary>
    public class ConsulHostedService : IHostedService
    {
        /// <summary>
        /// Consul 服务注册器
        /// </summary>
        private readonly IConsulServiceRegistry _consulServiceRegistry;
        
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<ConsulHostedService> _logger;

        /// <summary>
        /// 构造函数
        /// 通过依赖注入获取所需的服务
        /// </summary>
        /// <param name="consulServiceRegistry">Consul 服务注册器</param>
        /// <param name="logger">日志记录器</param>
        public ConsulHostedService(
            IConsulServiceRegistry consulServiceRegistry,
            ILogger<ConsulHostedService> logger)
        {
            _consulServiceRegistry = consulServiceRegistry;
            _logger = logger;
        }

        /// <summary>
        /// 启动服务时调用
        /// 在应用程序启动时自动将当前服务注册到 Consul
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>异步任务</returns>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Starting Consul service registration...");
            
            // 调用服务注册器进行服务注册
            var success = await _consulServiceRegistry.RegisterServiceAsync();
            
            if (success)
            {
                _logger.LogInformation("Consul service registration completed successfully");
            }
            else
            {
                _logger.LogError("Consul service registration failed");
            }
        }

        /// <summary>
        /// 停止服务时调用
        /// 在应用程序停止时自动从 Consul 注销当前服务
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>异步任务</returns>
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Starting Consul service deregistration...");
            
            // 调用服务注册器进行服务注销
            var success = await _consulServiceRegistry.DeregisterServiceAsync();
            
            if (success)
            {
                _logger.LogInformation("Consul service deregistration completed successfully");
            }
            else
            {
                _logger.LogError("Consul service deregistration failed");
            }
        }
    }
}